package com.newsinfo.service.impl;

import com.newsinfo.mapper.CategoryMapper;
import com.newsinfo.pojo.Category;
import com.newsinfo.pojo.Result;
import com.newsinfo.service.CategoryService;
import com.newsinfo.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;
    /**
     * 新增文章分类
     * @param category
     */
    @Override
    public Result add(Category category) {
        //判断是否存在该分类名称
        String categoryName = category.getCategoryName();
        List<Category> categoryList = list();
        for (Category categoryL : categoryList) {
            if (categoryL.getCategoryName().equals(categoryName)){
                return Result.error("已存在该分类");
            }
        }
        //从ThreadLocal中获取用户id
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        category.setCreateUser(userId);
        categoryMapper.add(category);
        return Result.success();
    }

    /**
     * 获取文章分类列表
     * @return
     */
    @Override
    public List<Category> list() {
        //获取id
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        return categoryMapper.list(userId);
    }

    /**
     * 获取文章分类详细
     * @param id
     * @return
     */
    @Override
    public Category findById(Integer id) {
        return categoryMapper.findById(id);
    }

    /**
     * 更新文章分类
     * @param category
     */
    @Override
    public void update(Category category) {
        categoryMapper.update(category);
    }

    /**
     * 删除文章分类
     * @param id
     */
    @Override
    public void deleteById(Integer id) {
        categoryMapper.delete(id);
    }
}
